package com.hjf.booking.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;

/**
 * @author hjf
 * @date 2021-03-17 14:01
 */
@Configuration
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private JsonLoginSuccessHandler jsonLoginSuccessHandler;

    @Autowired
    private JwtRefreshTokenHandler refreshTokenHandler;

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    @Autowired
    private TokenClearLogoutHandler tokenClearLogoutHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/image/**").permitAll()
                .antMatchers("/record/**").hasRole("USER")
                .and()
            .csrf().disable()
            .formLogin().disable()//禁用表单登录
            .cors()
            .and()
            //取消这个配置后，访问成功的接口删掉token后不能访问，没删的话可以正常访问
            //这个配置作用，同一个客户端，他的token不会消失，这样避免了重复校验所以一般不取消这个配置
            .securityContext().disable()
            .apply(new LoginConfigure<>()).loginSuccessHandler(jsonLoginSuccessHandler)
            .and()
            .apply(new JwtAuthenticationConfigure<>()).tokenValidSuccessHandler(refreshTokenHandler).permissiveRequestUrls("/logout")
            .and()
            .logout()
                .addLogoutHandler(tokenClearLogoutHandler)
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
            .and()
            .sessionManagement().disable();//禁用session
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(usernamePasswordAuthenticationProvider)
        .authenticationProvider(jwtAuthenticationProvider);
    }

}
